<?php

namespace app\admin\controller;

use app\admin\model\Admin;
use app\admin\model\Permission;
use app\admin\model\Role;
use think\Controller;
use think\Request;
use think\View;

/*
* Common
*/
class CommonController extends Controller
{
    public function _initialize()
    {
        $adminData = session('adminData', '');
        $this->showMenu($adminData);

        if ($adminData == '') {
            header('Location:' . url('admin/index/index','',''));
            exit;
        } else {
            View::share('adminData', $adminData);
        }

    }
    /*
     *检查权限
     */
    public function checkPermission(){


    }

    /**
     * SHOW THE ADMIN MENU
     */
    public function showMenu($adminData){
        $permission=Permission::all();
        $permission=$this->list_to_tree($permission);

        $data=array();
        if($adminData['id']!=1) {
            $admin = Admin::find($adminData['id']);
            $role = Role::find($admin->role_id);
            $role=json_decode($role->permission);

        }else{
            $role=array();
        }

        View::share('role',$role);
        View::share('permission',$permission);


    }
    public function list_to_tree($list, $child=array(), $parent_id = 0)
    {
        $child = array();
        if (!empty($list)) {
            foreach ($list as $k => &$v) {
                if ($v['parent_id'] == $parent_id) {
                    $v['child'] = $this->list_to_tree($list, $child, $v['id']);
                    $child[] = $v;
                    unset($this->list_to_tree[$k]);
                }
            }
        }
        return $child;
    }

}
